package com.SouthernWall_404.age_tool.common.Network.Packets.C2S;

import com.SouthernWall_404.age_tool.common.world.Entity.MusicBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class MusicBlockNBTC2SPacket {

    public CompoundTag modPack;
    public BlockPos blockPos;


    public MusicBlockNBTC2SPacket(FriendlyByteBuf buf) {
        this.blockPos=buf.readBlockPos();
        this.modPack=buf.readNbt();
    }


    public MusicBlockNBTC2SPacket(CompoundTag modPack, BlockPos blockPos)
    {
        this.blockPos=blockPos;
        this.modPack=modPack;
    }


    public void encode(FriendlyByteBuf buf) {
        buf.writeBlockPos(this.blockPos);
        buf.writeNbt(this.modPack);
    }

    public boolean handle(Supplier<NetworkEvent.Context> supplier)
    {
        var content=supplier.get();
        content.enqueueWork(() -> {

            Level level=content.getSender().level();
            BlockEntity blockEntity=level.getBlockEntity(this.blockPos);
            if(blockEntity!=null&&blockEntity instanceof MusicBlockEntity musicBlockEntity)
            {
                if(modPack!=null)
                {
                    musicBlockEntity.setNBT(modPack);
                }
            }

        });


        content.setPacketHandled(true);
        return true;
    }
}
